package com.joe.codemother.core;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.joe.codemother.ai.model.HtmlCodeResult;
import com.joe.codemother.ai.model.MultiFileCodeResult;
import com.joe.codemother.entity.enums.GenerateTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.charset.StandardCharsets;

public class CodeFileSaver {

    public static String FILE_ROOT_PATH = System.getProperty("user.dir")+"/temp/generate";

    public static File saveHtmlFile(HtmlCodeResult result, Long appId){
        String dirPath = buildUniqueDir(GenerateTypeEnum.HTML.getValue(),appId);
        String fileName = "index.html";
        saveFile(dirPath,fileName,result.getHtmlCode());
        return new File(dirPath);
    }

    public static File saveMultipartFile(MultiFileCodeResult result, Long appId){
        String dirPath = buildUniqueDir(GenerateTypeEnum.MULTI_FILE.getValue(),appId);
        saveFile(dirPath,"index.html",result.getHtmlCode());
        saveFile(dirPath,"style.css",result.getCssCode());
        saveFile(dirPath,"script.js",result.getJsCode());
        return new File(dirPath);
    }

    private static String buildUniqueDir(String generateType, Long appId){
        String fileName = StrUtil.format("{}_{}",generateType, appId);
        String filePath = FILE_ROOT_PATH+ File.separator + fileName;
        FileUtil.mkdir(filePath);
        return filePath;
    }

    private static void saveFile(String dirPath, String fileName, String content){
        FileUtil.writeString(content, dirPath + File.separator + fileName, StandardCharsets.UTF_8);
    }

}
